package com.gewu.pm.ui.fragment;

import android.Manifest;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.gewu.pm.R;
import com.gewu.pm.aop.Permissions;
import com.gewu.pm.aop.SingleClick;
import com.gewu.pm.app.AppActivity;
import com.gewu.pm.app.AppFragment;
import com.gewu.pm.bean.OrderBean;
import com.gewu.pm.ui.activity.order.PayOrderActivity;
import com.gewu.pm.ui.activity.order.PendingPaymentOrderDetailsActivity;
import com.gewu.pm.ui.adapter.PaymentOrderAdapter;
import com.gewu.pm.ui.dialog.CustomTimeDialog;
import com.gewu.pm.ui.popup.SelectTimePopup;
import com.gewu.pm.widget.FilterBar;
import com.gewu.pm.widget.StatusLayout;
import com.hjq.base.BaseDialog;
import com.hjq.base.BasePopupWindow;
import com.scwang.smart.refresh.layout.SmartRefreshLayout;
import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.scwang.smart.refresh.layout.listener.OnRefreshLoadMoreListener;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

/**
 * 代支付Fragment（复用）
 * type: 0-先款后货，1-货到付款，2-账期非对公
 */
public final class PaymentFragment extends AppFragment<AppActivity>
        implements OnRefreshLoadMoreListener,
        PaymentOrderAdapter.OnItemActionListener,
        com.hjq.base.BaseAdapter.OnItemClickListener {

    private FilterBar mFilterBar;
    private SmartRefreshLayout mRefreshLayout;
    private RecyclerView mRecyclerView;
    private StatusLayout mEmptyView;

    private PaymentOrderAdapter mAdapter;
    private List<OrderBean> mOrderList = new ArrayList<>();
    private List<OrderBean> mAllOrderList = new ArrayList<>();

    private int mTabType = 0;  // Fragment类型

    public static PaymentFragment newInstance(int type) {
        PaymentFragment fragment = new PaymentFragment();
        Bundle args = new Bundle();
        args.putInt("type", type);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_payment;
    }

    @Override
    protected void initView() {
        mFilterBar = findViewById(R.id.filter_bar);
        mRefreshLayout = findViewById(R.id.srl_refresh);
        mRecyclerView = findViewById(R.id.rv_list);
        mEmptyView = findViewById(R.id.empty_view);

        // 获取类型
        if (getArguments() != null) {
            mTabType = getArguments().getInt("type", 0);
        }

        // 设置RecyclerView
        mRecyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
        mAdapter = new PaymentOrderAdapter(getContext());
        mAdapter.setTabType(mTabType);
        mAdapter.setOnItemActionListener(this);
        mAdapter.setOnItemClickListener(this);  // ✅ 传this，实现接口处理
        mRecyclerView.setAdapter(mAdapter);

        // 设置刷新
        mRefreshLayout.setOnRefreshLoadMoreListener(this);

        // 设置搜索（通过FilterBar的搜索框）
        mFilterBar.getSearchEditText().addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
            }

            @Override
            public void afterTextChanged(Editable s) {
                searchOrders(s.toString().trim());
            }
        });
        // 设置 FilterBar 点击事件
        setOnClickListener(mFilterBar.getDateFilterLayout());
    }

    @Override
    protected void initData() {
        loadData();
    }

    @SingleClick
    @Override
    public void onClick(View view) {
        super.onClick(view);
        if (view == mFilterBar.getDateFilterLayout()) {
            List<String> str = new ArrayList<>();
            str.add("今日");
            str.add("昨天");
            str.add("本月");
            str.add("上月");
            str.add("最近7天");
            str.add("最近30天");
            str.add("自定义时间");

            // 获取当前显示的文本，用于设置选中状态
            String currentText = mFilterBar.getDateFilterTextView().getText().toString();

            new SelectTimePopup.Builder(getContext())
                    .setList(str)
                    .setSelectedItem(currentText)  // 根据当前显示的文本设置选中项
                    .setListener(new SelectTimePopup.OnListener() {
                        @Override
                        public void onSelected(BasePopupWindow popupWindow, String category) {
                            if ("自定义时间".equals(category)) {
                                // 显示自定义时间选择对话框
                                showCustomTimeDialog();
                            } else {
                                toast(category);
                                // 更新 FilterBar 显示的日期文本
                                mFilterBar.setDateFilterText(category);
                            }
                        }
                    })
                    .showAsDropDown(mFilterBar.getDateFilterLayout());
        }
    }

    /**
     * 列表项点击
     */
    @Override
    public void onItemClick(RecyclerView recyclerView, View itemView, int position) {
        OrderBean order = mAdapter.getItem(position);
        // 跳转到订单详情
        PendingPaymentOrderDetailsActivity.start(getContext(), order.getId());
    }
    /**
     * 显示自定义时间选择对话框
     */
    private void showCustomTimeDialog() {
        new CustomTimeDialog.Builder(getContext())
                .setListener(new CustomTimeDialog.OnListener() {
                    @Override
                    public void onSelected(BaseDialog dialog, int startYear, int startMonth, int startDay,
                                           int endYear, int endMonth, int endDay) {
                        // 格式化日期显示
                        String startDate = startYear + "-" + String.format("%02d", startMonth) + "-" + String.format("%02d", startDay);
                        String endDate = endYear + "-" + String.format("%02d", endMonth) + "-" + String.format("%02d", endDay);
                        String timeRange = startDate + " 至 " + endDate;

                        // 更新 FilterBar 显示的日期文本
                        mFilterBar.setDateFilterText(timeRange);
                        toast("已选择时间范围：" + timeRange);
                    }

                    @Override
                    public void onCancel(BaseDialog dialog) {
                        // 取消选择
                    }
                })
                .show();
    }

    /**
     * 搜索订单（模糊搜索）
     */
    private void searchOrders(String keyword) {
        if (TextUtils.isEmpty(keyword)) {
            mOrderList = new ArrayList<>(mAllOrderList);
        } else {
            mOrderList.clear();
            for (OrderBean order : mAllOrderList) {
                if (order.getTerminalName().contains(keyword) ||
                        order.getOrderNo().contains(keyword)) {
                    mOrderList.add(order);
                }
            }
        }

        mAdapter.setData(mOrderList);

        // 显示/隐藏EmptyView
        if (mOrderList.isEmpty()) {
            mEmptyView.show();
        } else {
            mEmptyView.hide();
        }
    }
    /**
     * 加载数据
     */
    private void loadData() {
        // 生成测试数据
        mAllOrderList.clear();
        Random random = new Random();

        for (int i = 0; i < 15; i++) {
            OrderBean order = new OrderBean();
            order.setId("order_" + i);
            order.setTerminalName("终端-" + (1872 + i) + "a-" + (i % 10));
            order.setCreateTime("2025-09-14 15:0" + i + ":41");
            order.setCreator("霍辉");
            order.setOrderNo("456711086789" + (33 + i));
            order.setVehicleCode("A29287" + i);
            order.setDeliveryMerchant("杭州小配送" + (18 + i) + "号车");
            order.setSalesperson("霍辉");
            order.setSalesRegion("杭州-滨江");
            order.setAmount("¥" + (1000 + random.nextInt(2000)) + "." + random.nextInt(100));
            order.setPhone("138" + String.format("%08d", random.nextInt(100000000)));

            // 只在先款后货Tab有倒计时（40%概率）
            if (mTabType == 0 && random.nextInt(100) < 40) {
                order.setCountdown(30 + random.nextInt(271));  // 30-300秒
            } else {
                order.setCountdown(0);
            }

            mAllOrderList.add(order);
        }

        mOrderList = new ArrayList<>(mAllOrderList);
        mAdapter.setData(mOrderList);

        // 显示/隐藏EmptyView
        if (mOrderList.isEmpty()) {
            mEmptyView.show();
        } else {
            mEmptyView.hide();
        }
    }

    @Override
    public void onRefresh(@NonNull RefreshLayout refreshLayout) {
        mAdapter.setPageNumber(1);
        loadData();
        refreshLayout.finishRefresh();
    }

    @Override
    public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
        mAdapter.setPageNumber(mAdapter.getPageNumber() + 1);
        // TODO: 加载更多
        refreshLayout.finishLoadMore();
    }

    @Override
    public void onPhoneClick(String phone) {
        // 拨打电话
        callPhone(phone);
    }

    @Override
    public void onPayClick(int position, OrderBean order) {
        // 跳转到支付页面
        PayOrderActivity.start(getContext(), order.getOrderNo());
    }

    /**
     * 拨打电话（需要权限）
     */
    @Permissions({Manifest.permission.CALL_PHONE})
    private void callPhone(String phone) {
        try {
            Intent intent = new Intent(Intent.ACTION_CALL);
            intent.setData(Uri.parse("tel:" + phone));
            startActivity(intent);
        } catch (Exception e) {
            toast(getString(R.string.call_permission_denied));
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        if (mAdapter != null) {
            mAdapter.startCountdown();
        }
    }

    @Override
    public void onPause() {
        super.onPause();
        if (mAdapter != null) {
            mAdapter.stopCountdown();
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (mAdapter != null) {
            mAdapter.stopCountdown();
        }
    }

}

